package com.company.cloud.pay.modules.pay.service.impl;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.cloud.pay.constant.ThirdPayConfirmWayEnum;
import com.company.cloud.pay.modules.api.response.PayOrderQueryResponse;
import com.company.cloud.pay.modules.base.entity.PayPaymentOrderInfo;
import com.company.cloud.pay.modules.base.service.PayPaymentOrderInfoService;
import com.company.cloud.pay.modules.pay.service.PaymentOrderService;
import com.company.cloud.pay.modules.third.models.ThirdPayNotifyResp;


@Service
public class PaymentOrderServiceImpl implements PaymentOrderService{
	
	
	@Autowired
	private PayPaymentOrderInfoService payPaymentOrderInfoService;
	

	@Override
	public void notifyCallBack(ThirdPayConfirmWayEnum confirmWay,String serviceCode, String companyNo,ThirdPayNotifyResp data) {
		PayPaymentOrderInfo entity=null;
		if(StringUtils.isEmpty(data.getAttach())) {
			entity=this.getPaymentOrderById(serviceCode, companyNo, data.getAttach());
		}else {
			entity=this.getPaymentOrderById(serviceCode, companyNo, data.getOutTradeNo());
		}
		if(entity!=null && this.isUpdate(entity.getThirdSteteConfirmWay(), confirmWay)) {
			entity.setState(data.getState());
			entity.setThirdSn(data.getTransactionId());
			entity.setThirdStete(data.getResultCode());
			entity.setThirdRemark(data.getResultCode());
			entity.setThirdSteteConfirmWay(confirmWay.getCode());
			entity.setThirdEditDate(LocalDateTime.now());
			entity.setThirdEditIp("");
			payPaymentOrderInfoService.updateById(entity);
		}
		
		
	}
	
	
	private boolean isUpdate(String confirmWay,ThirdPayConfirmWayEnum confirmWay2) {
		if(StringUtils.isEmpty(confirmWay)) {
			return true;
		}
		int _confirmWay=Integer.parseInt(confirmWay);
		int _confirmWay2=Integer.parseInt(confirmWay2.getCode());
		if(_confirmWay2>_confirmWay) {
			return true;
		}else {
			return false;
		}
	}
	
	
	
	private PayPaymentOrderInfo getPaymentOrderByBizSN(String serviceCode, String companyNo, String outSN) {
		PayPaymentOrderInfo entity= payPaymentOrderInfoService.getOne(
				new QueryWrapper<PayPaymentOrderInfo>()
				.eq("company_no", companyNo)
				.eq("service_code", serviceCode)
				.eq("out_sn", outSN)
		);
		return entity;
	}
	
	private PayPaymentOrderInfo getPaymentOrderById(String serviceCode, String companyNo, String attach) {
		PayPaymentOrderInfo entity= payPaymentOrderInfoService.getOne(
				new QueryWrapper<PayPaymentOrderInfo>()
				.eq("company_no", companyNo)
				.eq("service_code", serviceCode)
				.eq("sn", attach)
		);
		return entity;
	}

	@Override
	public void orderQueryCallBack(PayOrderQueryResponse data) {
		
	}

}
